package com.base.power.demo.sys.service;

import com.base.power.demo.common.base.dao.GenericDao;
import com.base.power.demo.common.base.service.GenericService;
import com.base.power.demo.sys.dao.RoleDao;
import com.base.power.demo.sys.dao.RoleRelationTreeDao;
import com.base.power.demo.sys.dao.UserRelationRoleDao;
import com.base.power.demo.sys.entity.QueryUserRole;
import com.base.power.demo.sys.entity.RoleRelationTree;
import com.base.power.demo.sys.entity.Tree;
import com.base.power.demo.sys.entity.UserRole;
import com.base.power.demo.sys.vo.UserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 类描述：
 */
@Service
@Transactional(rollbackFor={IllegalArgumentException.class})
public class RoleService extends GenericService<UserRole,QueryUserRole> {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRelationRoleDao userRelationRoleDao;
    @Autowired
    private RoleRelationTreeDao roleRelationTreeDao;

    @Override
    protected GenericDao<UserRole, QueryUserRole> getDao() {
        return roleDao;
    }

    /**
     * 功能描述：根据角色来获取关联的菜单数据
     * @param entity
     * @return
     */
    public UserRole getRoleRelationTree(UserRole entity){
        return roleDao.getRoleRelationTree(entity);
    }

    /**
     * 功能描述：更新角色与菜单的关联关系的数据
     * @param entity
     * @return
     * @throws Exception
     */
    public boolean updateUserRole(UserRoleVo entity) throws Exception {
        entity.packagingTrees(entity.getTreeArray());
        List<Tree> treeList = entity.getTreeList();
        roleRelationTreeDao.removeTreeByRoleId(entity);
        for(Tree tree:treeList){
            roleRelationTreeDao.save(new RoleRelationTree(entity.getId(),tree.getId()));
        }
        return super.update(entity);
    }

    /**
     * 增加角色数据
     * @param entity 保存对象
     * @return
     * @throws Exception
     */
    public boolean saveUserRole(UserRoleVo entity) throws Exception {
        entity.packagingTrees(entity.getTreeArray());
        List<Tree> treeList = entity.getTreeList();
        boolean success = super.save(entity);
        for(Tree tree:treeList){
            roleRelationTreeDao.save(new RoleRelationTree(entity.getId(),tree.getId()));
        }
        return success;
    }

    /**
     * 功能描述：重写删除角色的方法，删除角色之前先删除该角色相关联的中间表的角色的数据
     * @param entityList
     * @return
     * @throws Exception
     */
    @Override
    public boolean removeBath(List<UserRole> entityList) throws Exception {
        for(UserRole userRole:entityList){
            userRelationRoleDao.removeByRoleId(userRole);
            roleRelationTreeDao.removeTreeByRoleId(userRole);
        }
        return super.removeBath(entityList);
    }


}
